package modbus

// checksum 校验和
func checksum(buf [13]byte) uint8 {
	length := len(buf)
	var result uint8
	result = 0
	for i := 6; i < length-1; i++ {
		result += buf[i]
	}

	return result
}

func Uint162Bytes(n uint16) []byte {
	return []byte{
		byte(n),
		byte(n >> 8),
	}
}

// MakeReadMachineConfigRequest 构造 读机台配置数据的 请求  address uint16, length uint16
func MakeReadMachineConfigRequest() []byte {
	// 00 00 00 00 00 06 01 03 00 01 00 02 f8
	// 00 00 00 00 00 06 01 03 1F 40 00 29 73
	// var req [13]byte
	req := [13]byte{0, 0, 0, 0, 0, 6, 1, 3, 0, 0, 0, 0, 0}

	address := uint16(8000)
	req[8] = byte(address >> 8)
	req[9] = byte(address)

	length := uint16(41)
	req[10] = byte(length >> 8)
	req[11] = byte(length)

	req[12] = checksum(req)
	return req[0:]
}

// MakeReadMachineStatusRequest 构造 读机台状态数据的 请求
func MakeReadMachineStatusRequest() []byte {
	// 00 00 00 00 00 06   01 03   00 01   00 02 f8
	// var req [13]byte
	req := [13]byte{0, 0, 0, 0, 0, 6, 1, 3, 40, 0, 0, 27, 0}

	address := uint16(4000)
	req[8] = byte(address >> 8)
	req[9] = byte(address)

	length := uint16(27)
	req[10] = byte(length >> 8)
	req[11] = byte(length)

	req[12] = checksum(req)
	return req[0:]
}

// MakeReadSpindleStatusRequest 构造 读纱锭状态数据的 请求
func MakeReadSpindleStatusRequest(offset uint16, count uint16) []byte {
	// 00 00 00 00 00 06 01 03 00 01 00 02 f8
	// var req [13]byte
	req := [13]byte{0, 0, 0, 0, 0, 6, 1, 3, 0, 0, 0, 0, 0}

	offset = 4100 + offset
	req[8] = byte(offset >> 8)
	req[9] = byte(offset)

	req[10] = byte(count >> 8)
	req[11] = byte(count)

	req[12] = checksum(req)
	return req[0:]
}

// MakeReadSpindleSpeedRequest 构造 读纱锭速度数据的 请求
func MakeReadSpindleSpeedRequest(offset uint16, count uint16) []byte {
	// 00 00 00 00 00 06 01 03 00 01 00 02 f8
	// var req [13]byte
	req := [13]byte{0, 0, 0, 0, 0, 6, 1, 3, 0, 1, 0, 2, 0}

	offset = 5000 + offset
	req[8] = byte(offset >> 8)
	req[9] = byte(offset)

	req[10] = byte(count >> 8)
	req[11] = byte(count)

	req[12] = checksum(req)
	return req[0:]
}
